<template>
    <div class="cart-store-header">
        <van-checkbox v-model="checked"/>
        <wing-blank class="store-names" @click.stop="handleRouteToStore">
            <van-image :height="20" :width="20" :radius="4" :src="store.logo"/>
            <span class="store-name">{{store.name}}</span>
            <van-icon name="arrow"/>
        </wing-blank>
    </div>
</template>

<script>
  import { Checkbox, Icon, Image, Toast } from "vant"
  import WingBlank from "@/components/WingBlank"
  import { store as Store } from "@mall/api-services"
  import { createNamespacedHelpers } from "vuex"

  import * as _ from "lodash"

  const { mapState, mapActions } = createNamespacedHelpers("cart")

  export default {
    name: "CartItemsHeader",
    components: {
      WingBlank,
      [Checkbox.name]: Checkbox,
      [Icon.name]: Icon,
      [Image.name]: Image,
    },
    props: {
      storeId: String,
    },
    data() {
      return {
        store: new Store.Store(),
      }
    },
    computed: {
      ...mapState({
        items({ items }) {
          const { storeId } = this
          return _.chain(items).filter(item => item.storeId === storeId).value()
        },
      }),
      itemIds() {
        const { items } = this
        return _.map(items, item => item.id)
      },
      checked: {
        get: function() {
          const { items } = this
          for (const item of items) {
            if (!item.checked) {
              return false
            }
          }
          return true
        },
        set: function(checked) {
          const { itemIds, checkItems, uncheckItems } = this
          Toast.loading()
          new Promise((resolve, reject) => {
            if (checked) {
              checkItems(itemIds).then(resolve).catch(reject)
            } else {
              uncheckItems(itemIds).then(resolve).catch(reject)
            }
          }).finally(() => Toast.clear())
        },
      },

    },
    created() {
      this.setStore()
    },
    methods: {
      ...mapActions(["checkItems", "uncheckItems"]),
      handleRouteToStore() {
        const { storeId } = this
        this.$router.push(`/stores/${storeId}`)
      },
      setStore() {
        const { storeId } = this
        Store.StoreServiceV1.getStore(storeId)
          .then(aStore => this.store = aStore)
      },
    },
  }
</script>

<style lang="scss" scoped>
    @import "../../styles/variables";

    .cart-store-header {
        display: flex;
        align-items: center;
        margin: 0 9px;
        padding: 9px 0;

        .store-names {
            display: inline-flex;
            align-items: center;
        }

        .store-name {
            font-weight: 700;
            margin-left: 4px;
        }

        .van-icon-arrow {
            color: $gray-5;
            top: 1px;
        }
    }

</style>
